home *** CD-ROM | disk | FTP | other *** search
/ The Very Best of Atari Inside / The Very Best of Atari Inside 1.iso / mint / mntlb20 / lib / scandir.c < prev    next >
C/C++ Source or Header  |  1991-04-13  |  2KB  |  78 lines

  1. /*
  2. **  SCANDIR
  3. **  Scan a directory, collecting all (selected) items into a an array.
  4. */
  5.  
  6. #include <stdlib.h>    /* for qsort */
  7. #include <sys/types.h>
  8. #include <sys/dir.h>
  9. #include <string.h>
  10.  
  11. #ifndef NULL
  12. #define NULL 0
  13. #endif
  14.  
  15. /* Initial guess at directory size. */
  16. #define INITIAL_SIZE    20
  17.  
  18.  
  19. int
  20. scandir(name, list, selector, sorter)
  21.     char          *name;
  22.     struct direct    ***list;
  23.     int             (*selector)();
  24.     int             (*sorter)();
  25. {
  26.     register struct direct     **names;
  27.     register struct direct      *entp;
  28.     register DIR      *dirp;
  29.     register int       i;
  30.     register int       size;
  31.  
  32.     /* Get initial list space and open directory. */
  33.     size = INITIAL_SIZE;
  34.     names = (struct direct **)malloc(size * sizeof names[0]);
  35.     if (names == NULL)
  36.     return -1;
  37.     dirp = opendir(name);
  38.     if (dirp == NULL)
  39.     return -1;
  40.  
  41.     /* Read entries in the directory. */
  42.     for (i = 0; entp = readdir(dirp); )
  43.     if (selector == NULL || (*selector)(entp)) {
  44.         /* User wants them all, or he wants this one. */
  45.         if (++i >= size) {
  46.         size <<= 1;
  47.         names = (struct direct **)
  48.             realloc((char *)names, size * sizeof names[0]);
  49.         if (names == NULL) {
  50.             closedir(dirp);
  51.             return -1;
  52.         }
  53.         }
  54.  
  55.         /* Copy the entry. */
  56.         names[i - 1] = (struct direct *)malloc(DIRSIZ(entp));
  57.         if (names[i - 1] == NULL) {
  58.         closedir(dirp);
  59.         return -1;
  60.         }
  61.         names[i - 1]->d_ino = entp->d_ino;
  62.         names[i - 1]->d_reclen = entp->d_reclen;
  63.         names[i - 1]->d_namlen = entp->d_namlen;
  64.         (void)strcpy(names[i - 1]->d_name, entp->d_name);
  65.     }
  66.  
  67.     /* Close things off. */
  68.     names[i] = NULL;
  69.     *list = names;
  70.     closedir(dirp);
  71.  
  72.     /* Sort? */
  73.     if (i && sorter)
  74.     qsort((char *)names, i, sizeof names[0], sorter);
  75.  
  76.     return i;
  77. }
  78.